<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Vue 响应式解析 | Justic</title><meta name="keywords" content="Vue"><meta name="author" content="Justic"><meta name="copyright" content="Justic"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="一、什么是响应式？当我们见到数据响应式的时候，总是有一个疑问，那就是什么是响应式？让我们先来看一下响应式意味着什么： let num &#x3D; 100console.log(num )console.log(num * 2)&#x2F;&#x2F;当前输出为 100 200num &#x3D; 200 &#x2F;&#x2F;定义新值&#x2F;&#x2F; 新的执行结果为 200 400 如上代码所示：num有一个初始的值100 当我们给它赋予了新的值之后，这段代码会自">
<meta property="og:type" content="article">
<meta property="og:title" content="Vue 响应式解析">
<meta property="og:url" content="http://example.com/2022/10/20/Vue/Vue%20%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/Vue%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/index.html">
<meta property="og:site_name" content="Justic">
<meta property="og:description" content="一、什么是响应式？当我们见到数据响应式的时候，总是有一个疑问，那就是什么是响应式？让我们先来看一下响应式意味着什么： let num &#x3D; 100console.log(num )console.log(num * 2)&#x2F;&#x2F;当前输出为 100 200num &#x3D; 200 &#x2F;&#x2F;定义新值&#x2F;&#x2F; 新的执行结果为 200 400 如上代码所示：num有一个初始的值100 当我们给它赋予了新的值之后，这段代码会自">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/z8/wallhaven-z82evv.jpg">
<meta property="article:published_time" content="2022-10-20T12:05:37.000Z">
<meta property="article:modified_time" content="2022-10-21T06:12:35.106Z">
<meta property="article:author" content="Justic">
<meta property="article:tag" content="Vue">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/z8/wallhaven-z82evv.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="http://example.com/2022/10/20/Vue/Vue%20%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/Vue%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Vue 响应式解析',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-10-21 14:12:35'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.css" /><!-- hexo injector head_end end --><meta name="generator" content="Hexo 6.2.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://portrait.gitee.com/uploads/avatars/user/2982/8948190_JIAXInT_1624177607.png!avatar200" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">25</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">2</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">3</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/project/"><i class="fa-fw fas fa-images"></i><span> 项目</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于笔者</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/z8/wallhaven-z82evv.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Justic</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/project/"><i class="fa-fw fas fa-images"></i><span> 项目</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于笔者</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Vue 响应式解析</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-10-20T12:05:37.000Z" title="发表于 2022-10-20 20:05:37">2022-10-20</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-10-21T06:12:35.106Z" title="更新于 2022-10-21 14:12:35">2022-10-21</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Vue/">Vue</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.6k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>10分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Vue 响应式解析"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span><span class="post-meta-separator">|</span><span class="post-meta-commentcount"><i class="far fa-comments fa-fw post-meta-icon"></i><span class="post-meta-label">评论数:</span><a href="/2022/10/20/Vue/Vue%20%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/Vue%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/2022/10/20/Vue/Vue%20%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/Vue%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/" itemprop="commentCount"><i class="fa-solid fa-spinner fa-spin"></i></span></a></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="一、什么是响应式？"><a href="#一、什么是响应式？" class="headerlink" title="一、什么是响应式？"></a>一、什么是响应式？</h1><p>当我们见到数据响应式的时候，总是有一个疑问，那就是什么是响应式？让我们先来看一下响应式意味着什么：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> num = <span class="number">100</span></span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(num )</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(num * <span class="number">2</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">//当前输出为 100 200</span></span><br><span class="line"></span><br><span class="line">num = <span class="number">200</span> <span class="comment">//定义新值</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 新的执行结果为 200 400</span></span><br></pre></td></tr></table></figure>
<p>如上代码所示：num有一个初始的值100 当我们给它赋予了新的值之后，这段代码会自动的重新执行，获得新的结果。</p>
<p><strong>这样一种可以自动响应数据变量的代码机制，我们就称之为是响应式的</strong></p>
<h1 id="二、响应式函数设计"><a href="#二、响应式函数设计" class="headerlink" title="二、响应式函数设计"></a>二、响应式函数设计</h1><p>上面仅仅是变量的响应式，那如果是一个对象的响应式呢？<br>首先，执行的代码可能不止一行代码，所以我们所以我们可以将这些代码放到一个函数中，那么我们的问题就变成了，当数据发生变化时，自动去执行一个函数。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 对象的响应式</span></span><br><span class="line"><span class="keyword">const</span> obj = &#123;</span><br><span class="line">  <span class="attr">name</span>: <span class="string">&quot;Justic&quot;</span>,</span><br><span class="line">  <span class="attr">age</span>: <span class="number">18</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">foo</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(obj.<span class="property">name</span>)</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(obj.<span class="property">age</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">bar</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;Hello Word&quot;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 修改obj对象</span></span><br><span class="line">obj.<span class="property">name</span> = <span class="string">&quot;kobe&quot;</span></span><br><span class="line">obj.<span class="property">age</span> = <span class="number">20</span></span><br></pre></td></tr></table></figure>
<p>但是有一个问题：在开发中我们是有很多的函数的，我们如何区分一个函数需要响应式，还是不需要响应式呢？</p>
<p>很明显，上面代码中的函数 foo 需要在obj的name发生变化时，重新执行，做出相应。</p>
<p>但是bar函数是一个完全独立于obj的函数，它不需要执行任何响应式的操作。</p>
<p>这就需要我们来设计一个响应式函数了。</p>
<h1 id="三、响应式函数的实现watchFn"><a href="#三、响应式函数的实现watchFn" class="headerlink" title="三、响应式函数的实现watchFn"></a>三、响应式函数的实现watchFn</h1><p>我们可以封装一个新的函数watchFn</p>
<p>凡是传入到watchFn中的函数，就是需要响应式的</p>
<p>而其他默认的定义的函数就是不需要响应式的</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 设置一个专门执行响应式函数的一个函数</span></span><br><span class="line"><span class="keyword">const</span> reactiveFns = []</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">watchFn</span>(<span class="params">fn</span>) &#123;</span><br><span class="line">    <span class="comment">//将收集到的函数统一放到reactiveFns数组中</span></span><br><span class="line">    reactiveFns.<span class="title function_">push</span>(fn)</span><br><span class="line">    <span class="title function_">fn</span>()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样我们调用需要响应式的函数时，就可以以下面的方式调用：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="title function_">watchFn</span>(<span class="keyword">function</span> <span class="title function_">foo</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;foo:&quot;</span>, obj.<span class="property">name</span>)</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;foo&quot;</span>, obj.<span class="property">age</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h1 id="四、响应式依赖的收集"><a href="#四、响应式依赖的收集" class="headerlink" title="四、响应式依赖的收集"></a>四、响应式依赖的收集</h1><p>目前我们收集到的依赖都是放到reactiveFns数组中来保存的，但是这样会存在一些数据管理的问题：</p>
<ul>
<li>我们在实际开发中需要监听很多对象的响应式；</li>
<li>这些对象需要监听的也不止一个属性，它们很多属性的变化，都会有对应的响应式函数；</li>
<li>我们不可能在全局维护一大堆的数组来保存这些响应函数；</li>
</ul>
<p>那么该如何解决呢？我们可以设计一个类，这个类用于管理某一个对象的某一个属性的所有响应式函数，相当于替代了原先的reactiveFns数组。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Depend</span> &#123;</span><br><span class="line">  <span class="title function_">constructor</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">reactiveFns</span> = []</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//函数收集</span></span><br><span class="line">  <span class="title function_">addDepend</span>(<span class="params">fn</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (fn) &#123;</span><br><span class="line">      <span class="variable language_">this</span>.<span class="property">reactiveFns</span>.<span class="title function_">push</span>(fn)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//通知函数发生变化</span></span><br><span class="line">  <span class="title function_">notify</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">reactiveFns</span>.<span class="title function_">forEach</span>(<span class="function"><span class="params">fn</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="title function_">fn</span>()</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们的watchFn函数也就变成了这样：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> dep = <span class="keyword">new</span> <span class="title class_">Depend</span>()</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">watchFn</span>(<span class="params">fn</span>) &#123;</span><br><span class="line">  dep.<span class="title function_">addDepend</span>(fn)</span><br><span class="line">  <span class="title function_">fn</span>()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="五、监听对象的变化"><a href="#五、监听对象的变化" class="headerlink" title="五、监听对象的变化"></a>五、监听对象的变化</h1><p>那么接下来我们就需要监听对象的变化，对象的属性发生变化时，我们就需要触发Depend 类里的notify()函数来通知函数发生变化。</p>
<p>那我们该如何监听对象呢？有如下两种方式：</p>
<ul>
<li>方式一：通过 Object.defineProperty的方式（vue2采用的方式）</li>
<li>方式二：通过new Proxy的方式（vue3采用的方式）；</li>
</ul>
<p>这里我们先采用方式一的Object.defineProperty的方式来监听：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 方案一: Object.defineProperty() -&gt; Vue2</span></span><br><span class="line"><span class="title class_">Object</span>.<span class="title function_">keys</span>(obj).<span class="title function_">forEach</span>(<span class="function"><span class="params">key</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">let</span> value = obj[key]</span><br><span class="line"></span><br><span class="line">  <span class="title class_">Object</span>.<span class="title function_">defineProperty</span>(obj, key, &#123;</span><br><span class="line">    <span class="attr">set</span>: <span class="keyword">function</span>(<span class="params">newValue</span>) &#123;</span><br><span class="line">      value = newValue</span><br><span class="line">      <span class="comment">//对象属性发生改变，执行notify()函数</span></span><br><span class="line">      dep.<span class="title function_">notify</span>()</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">get</span>: <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> value</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h1 id="六、对象的依赖管理"><a href="#六、对象的依赖管理" class="headerlink" title="六、对象的依赖管理"></a>六、对象的依赖管理</h1><p>我们目前是创建了一个Depend对象，用来管理对于name变化需要监听的响应函数：</p>
<ul>
<li>但是实际开发中我们会有不同的对象，另外会有不同的属性需要管理；</li>
<li>我们如何可以使用一种数据结构来管理不同对象的不同依赖关系呢？</li>
</ul>
<p><strong>我们可以通过WeakMap管理这种响应式的数据依赖</strong></p>
<p>要达到对象中每个属性的响应式，需要通过以下方式对dep对象进行管理：</p>
<ul>
<li>每个obj对象的每一个属性都要有与之对应的dep对象，</li>
<li>同一个对象的多个属性的dep对象是存放一个map对象中</li>
<li>多个对象的map对象, 会被存放到一个objMap的对象中</li>
</ul>
<p>数据结构如下图所示：</p>
<p><img src= "" data-lazy-src="/2022/10/20/Vue/Vue%20%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/Vue%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/image-20221020223106085.png" alt="image-20221020223106085"></p>
<h1 id="七、对象依赖管理的实现"><a href="#七、对象依赖管理的实现" class="headerlink" title="七、对象依赖管理的实现"></a>七、对象依赖管理的实现</h1><p>我们可以写一个getDepend函数专门来管理这种依赖关系：</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 封装一个函数: 负责通过obj的key获取对应的Depend对象</span></span><br><span class="line"><span class="keyword">const</span> objMap = <span class="keyword">new</span> <span class="title class_">WeakMap</span>()</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">getDepend</span>(<span class="params">obj, key</span>) &#123;</span><br><span class="line">  <span class="comment">// 1.根据对象obj, 找到对应的map对象</span></span><br><span class="line">  <span class="keyword">let</span> map = objMap.<span class="title function_">get</span>(obj)</span><br><span class="line">  <span class="keyword">if</span> (!map) &#123;</span><br><span class="line">    map = <span class="keyword">new</span> <span class="title class_">Map</span>()</span><br><span class="line">    objMap.<span class="title function_">set</span>(obj, map)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 2.根据key, 找到对应的depend对象</span></span><br><span class="line">  <span class="keyword">let</span> dep = map.<span class="title function_">get</span>(key)</span><br><span class="line">  <span class="keyword">if</span> (!dep) &#123;</span><br><span class="line">    dep = <span class="keyword">new</span> <span class="title class_">Depend</span>()</span><br><span class="line">    map.<span class="title function_">set</span>(key, dep)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> dep</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<p>这样我们就可以在Object.defineProperty()的set捕获器中调用getDepend()函数</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="title class_">Object</span>.<span class="title function_">keys</span>(obj).<span class="title function_">forEach</span>(<span class="function"><span class="params">key</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">let</span> value = obj[key]</span><br><span class="line"></span><br><span class="line">  <span class="title class_">Object</span>.<span class="title function_">defineProperty</span>(obj, key, &#123;</span><br><span class="line">    <span class="attr">set</span>: <span class="keyword">function</span>(<span class="params">newValue</span>) &#123;</span><br><span class="line">      value = newValue</span><br><span class="line">      <span class="keyword">const</span> dep = <span class="title function_">getDepend</span>(obj, key)</span><br><span class="line">      dep.<span class="title function_">notify</span>()</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">get</span>: <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">return</span> value</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h1 id="八、正确的依赖收集"><a href="#八、正确的依赖收集" class="headerlink" title="八、正确的依赖收集"></a>八、正确的依赖收集</h1><p>我们之前收集依赖都是在watchFn中，但是这种收集依赖的方式我们根本不知道是哪一个key的哪一个depend需要收集依赖，你只能针对一个单独的depend对象来添加你的依赖对象。</p>
<p>那么正确的应该是在哪里收集呢？应该在我们调用了Object.defineProperty()的get捕获器时：</p>
<p><strong>如果一个函数中使用了某个对象的key，那么它应该被收集依赖</strong></p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 设置一个专门执行响应式函数的一个函数</span></span><br><span class="line"><span class="keyword">let</span> reactiveFn = <span class="literal">null</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">watchFn</span>(<span class="params">fn</span>) &#123;</span><br><span class="line">  reactiveFn = fn</span><br><span class="line">  <span class="title function_">fn</span>()</span><br><span class="line">  reactiveFn = <span class="literal">null</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="title class_">Object</span>.<span class="title function_">keys</span>(obj).<span class="title function_">forEach</span>(<span class="function"><span class="params">key</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">let</span> value = obj[key]</span><br><span class="line"></span><br><span class="line">  <span class="title class_">Object</span>.<span class="title function_">defineProperty</span>(obj, key, &#123;</span><br><span class="line">    <span class="attr">set</span>: <span class="keyword">function</span>(<span class="params">newValue</span>) &#123;</span><br><span class="line">      value = newValue</span><br><span class="line">      <span class="keyword">const</span> dep = <span class="title function_">getDepend</span>(obj, key)</span><br><span class="line">      dep.<span class="title function_">notify</span>()</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">get</span>: <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">      <span class="comment">// 拿到obj -&gt; key</span></span><br><span class="line">      <span class="comment">// 找到对应的obj对象的key对应的dep对象</span></span><br><span class="line">      <span class="keyword">const</span> dep = <span class="title function_">getDepend</span>(obj, key)</span><br><span class="line">      dep.<span class="title function_">addDepend</span>(reactiveFn)</span><br><span class="line"></span><br><span class="line">      <span class="keyword">return</span> value</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h1 id="九、对Depend重构"><a href="#九、对Depend重构" class="headerlink" title="九、对Depend重构"></a>九、对Depend重构</h1><p>但这里有两个问题：</p>
<ol>
<li>如果函数中有用到两次key，比如name，那么这个函数会被收集两次；</li>
<li>我们并不希望将添加reactiveFn放到get中，因为它是属于Dep的行为；</li>
</ol>
<p>所以我们要对Depend类进行重构：</p>
<ol>
<li>解决问题一的方法：不使用数组，而是使用Set；</li>
<li>解决问题二的方法：添加一个新的方法，用于收集依赖；</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Depend</span> &#123;</span><br><span class="line">    <span class="title function_">constructor</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="comment">//将数组结构替换为set() set特性为无序且唯一</span></span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">reactiveFns</span> = <span class="keyword">new</span> <span class="title class_">Set</span>()</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="title function_">addDepend</span>(<span class="params">fn</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (fn) &#123;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="property">reactiveFns</span>.<span class="title function_">add</span>(fn)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//添加新的方法用于依赖收集</span></span><br><span class="line">    <span class="title function_">depend</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (reactiveFn) &#123;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="property">reactiveFns</span>.<span class="title function_">add</span>(reactiveFn)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="title function_">notify</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">reactiveFns</span>.<span class="title function_">forEach</span>(<span class="function"><span class="params">fn</span> =&gt;</span> &#123;</span><br><span class="line">            <span class="title function_">fn</span>()</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这样我们就可以在get捕获器中调用depend(）方法</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="attr">get</span>: <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">            <span class="comment">// 拿到obj -&gt; key</span></span><br><span class="line">            <span class="comment">// 找到对应的obj对象的key对应的dep对象</span></span><br><span class="line">            <span class="keyword">const</span> dep = <span class="title function_">getDepend</span>(obj, key)</span><br><span class="line">                <span class="comment">// dep.addDepend(reactiveFn)</span></span><br><span class="line">            dep.<span class="title function_">depend</span>()</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> value</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure>

<h1 id="十、创建响应式对象"><a href="#十、创建响应式对象" class="headerlink" title="十、创建响应式对象"></a>十、创建响应式对象</h1><p>我们目前的响应式是针对于obj一个对象的，我们可以创建出来一个reactive()函数，针对所有的对象都可以变成响应式对象：</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">reactive</span>(<span class="params">obj</span>) &#123;</span><br><span class="line">  <span class="title class_">Object</span>.<span class="title function_">keys</span>(obj).<span class="title function_">forEach</span>(<span class="function"><span class="params">key</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">let</span> value = obj[key]</span><br><span class="line">  </span><br><span class="line">    <span class="title class_">Object</span>.<span class="title function_">defineProperty</span>(obj, key, &#123;</span><br><span class="line">      <span class="attr">set</span>: <span class="keyword">function</span>(<span class="params">newValue</span>) &#123;</span><br><span class="line">        value = newValue</span><br><span class="line">        <span class="keyword">const</span> dep = <span class="title function_">getDepend</span>(obj, key)</span><br><span class="line">        dep.<span class="title function_">notify</span>()</span><br><span class="line">      &#125;,</span><br><span class="line">      <span class="attr">get</span>: <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="comment">// 拿到obj -&gt; key</span></span><br><span class="line">        <span class="comment">// 找到对应的obj对象的key对应的dep对象</span></span><br><span class="line">        <span class="keyword">const</span> dep = <span class="title function_">getDepend</span>(obj, key)</span><br><span class="line">        <span class="comment">// dep.addDepend(reactiveFn)</span></span><br><span class="line">        dep.<span class="title function_">depend</span>()</span><br><span class="line">  </span><br><span class="line">        <span class="keyword">return</span> value</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;)  </span><br><span class="line">  <span class="keyword">return</span> obj</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这样我们就可以用reactive()函数包裹对象，使其变为响应式对象</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> obj = <span class="title function_">reactive</span>(&#123;</span><br><span class="line">  <span class="attr">name</span>: <span class="string">&quot;Justic&quot;</span>,</span><br><span class="line">  <span class="attr">age</span>: <span class="number">18</span>,</span><br><span class="line">  <span class="attr">address</span>: <span class="string">&quot;深圳市&quot;</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h1 id="十一、Vue2、Vue3响应式原理"><a href="#十一、Vue2、Vue3响应式原理" class="headerlink" title="十一、Vue2、Vue3响应式原理"></a>十一、Vue2、Vue3响应式原理</h1><p>我们前面所实现的响应式代码，其实就是Vue2中的响应式原理，Vue2通过Object.defineProerty的方式来实现对象属性的监听。</p>
<p><strong>而Vue3主要是通过Proxy来监听数据的变化以及收集相关的依赖的</strong></p>
<p>我们可以使用Proxy来对reactive()函数进行重构：</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 方式二: new Proxy() -&gt; Vue3</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">reactive</span>(<span class="params">obj</span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> objProxy = <span class="keyword">new</span> <span class="title class_">Proxy</span>(obj, &#123;</span><br><span class="line">    <span class="attr">set</span>: <span class="keyword">function</span>(<span class="params">target, key, newValue, receiver</span>) &#123;</span><br><span class="line">      <span class="title class_">Reflect</span>.<span class="title function_">set</span>(target, key, newValue, receiver)</span><br><span class="line">      <span class="keyword">const</span> dep = <span class="title function_">getDepend</span>(target, key)</span><br><span class="line">      dep.<span class="title function_">notify</span>()</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">get</span>: <span class="keyword">function</span>(<span class="params">target, key, receiver</span>) &#123;</span><br><span class="line">      <span class="keyword">const</span> dep = <span class="title function_">getDepend</span>(target, key)</span><br><span class="line">      dep.<span class="title function_">depend</span>()</span><br><span class="line">      <span class="keyword">return</span> <span class="title class_">Reflect</span>.<span class="title function_">get</span>(target, key, receiver)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br><span class="line">  <span class="keyword">return</span> objProxy</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在setter和getter方法中的逻辑和前面的Object.defineProerty是一致的。</p>
<p><strong>接下来让我们看一下完整代码吧：</strong></p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Depend</span> &#123;</span><br><span class="line">    <span class="title function_">constructor</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">reactiveFns</span> = <span class="keyword">new</span> <span class="title class_">Set</span>()</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="title function_">addDepend</span>(<span class="params">fn</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (fn) &#123;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="property">reactiveFns</span>.<span class="title function_">add</span>(fn)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="title function_">depend</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (reactiveFn) &#123;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="property">reactiveFns</span>.<span class="title function_">add</span>(reactiveFn)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="title function_">notify</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">reactiveFns</span>.<span class="title function_">forEach</span>(<span class="function"><span class="params">fn</span> =&gt;</span> &#123;</span><br><span class="line">            <span class="title function_">fn</span>()</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 设置一个专门执行响应式函数的一个函数</span></span><br><span class="line"><span class="keyword">let</span> reactiveFn = <span class="literal">null</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">watchFn</span>(<span class="params">fn</span>) &#123;</span><br><span class="line">    reactiveFn = fn</span><br><span class="line">    <span class="title function_">fn</span>()</span><br><span class="line">    reactiveFn = <span class="literal">null</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 封装一个函数: 负责通过obj的key获取对应的Depend对象</span></span><br><span class="line"><span class="keyword">const</span> objMap = <span class="keyword">new</span> <span class="title class_">WeakMap</span>()</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">getDepend</span>(<span class="params">obj, key</span>) &#123;</span><br><span class="line">    <span class="comment">// 1.根据对象obj, 找到对应的map对象</span></span><br><span class="line">    <span class="keyword">let</span> map = objMap.<span class="title function_">get</span>(obj)</span><br><span class="line">    <span class="keyword">if</span> (!map) &#123;</span><br><span class="line">        map = <span class="keyword">new</span> <span class="title class_">Map</span>()</span><br><span class="line">        objMap.<span class="title function_">set</span>(obj, map)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 2.根据key, 找到对应的depend对象</span></span><br><span class="line">    <span class="keyword">let</span> dep = map.<span class="title function_">get</span>(key)</span><br><span class="line">    <span class="keyword">if</span> (!dep) &#123;</span><br><span class="line">        dep = <span class="keyword">new</span> <span class="title class_">Depend</span>()</span><br><span class="line">        map.<span class="title function_">set</span>(key, dep)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> dep</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方案一: Object.defineProperty() -&gt; Vue2</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">reactiveV2</span>(<span class="params">obj</span>) &#123;</span><br><span class="line">    <span class="title class_">Object</span>.<span class="title function_">keys</span>(obj).<span class="title function_">forEach</span>(<span class="function"><span class="params">key</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> value = obj[key]</span><br><span class="line"></span><br><span class="line">        <span class="title class_">Object</span>.<span class="title function_">defineProperty</span>(obj, key, &#123;</span><br><span class="line">            <span class="attr">set</span>: <span class="keyword">function</span>(<span class="params">newValue</span>) &#123;</span><br><span class="line">                value = newValue</span><br><span class="line">                <span class="keyword">const</span> dep = <span class="title function_">getDepend</span>(obj, key)</span><br><span class="line">                dep.<span class="title function_">notify</span>()</span><br><span class="line">            &#125;,</span><br><span class="line">            <span class="attr">get</span>: <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">                <span class="comment">// 拿到obj -&gt; key</span></span><br><span class="line">                <span class="comment">// 找到对应的obj对象的key对应的dep对象</span></span><br><span class="line">                <span class="keyword">const</span> dep = <span class="title function_">getDepend</span>(obj, key)</span><br><span class="line">                    <span class="comment">// dep.addDepend(reactiveFn)</span></span><br><span class="line">                dep.<span class="title function_">depend</span>()</span><br><span class="line"></span><br><span class="line">                <span class="keyword">return</span> value</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="keyword">return</span> obj</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方式二: new Proxy() -&gt; Vue3</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">reactiveV3</span>(<span class="params">obj</span>) &#123;</span><br><span class="line">    <span class="keyword">const</span> objProxy = <span class="keyword">new</span> <span class="title class_">Proxy</span>(obj, &#123;</span><br><span class="line">        <span class="attr">set</span>: <span class="keyword">function</span>(<span class="params">target, key, newValue, receiver</span>) &#123;</span><br><span class="line">            <span class="comment">// target[key] = newValue</span></span><br><span class="line">            <span class="title class_">Reflect</span>.<span class="title function_">set</span>(target, key, newValue, receiver)</span><br><span class="line">            <span class="keyword">const</span> dep = <span class="title function_">getDepend</span>(target, key)</span><br><span class="line">            dep.<span class="title function_">notify</span>()</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="attr">get</span>: <span class="keyword">function</span>(<span class="params">target, key, receiver</span>) &#123;</span><br><span class="line">            <span class="keyword">const</span> dep = <span class="title function_">getDepend</span>(target, key)</span><br><span class="line">            dep.<span class="title function_">depend</span>()</span><br><span class="line">            <span class="keyword">return</span> <span class="title class_">Reflect</span>.<span class="title function_">get</span>(target, key, receiver)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="keyword">return</span> objProxy</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// ========================= 业务代码 ========================</span></span><br><span class="line"><span class="keyword">const</span> obj = <span class="title function_">reactiveV2</span>(&#123;</span><br><span class="line">    <span class="attr">name</span>: <span class="string">&quot;Justic&quot;</span>,</span><br><span class="line">    <span class="attr">age</span>: <span class="number">18</span>,</span><br><span class="line">    <span class="attr">address</span>: <span class="string">&quot;深圳市&quot;</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> user = <span class="title function_">reactiveV3</span>(&#123;</span><br><span class="line">    <span class="attr">name</span>:<span class="string">&#x27;abc&#x27;</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://example.com">Justic</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://example.com/2022/10/20/Vue/Vue%20%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/Vue%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/">http://example.com/2022/10/20/Vue/Vue 响应式解析/Vue响应式解析/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://justicc.top/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://example.com" target="_blank">Justic</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Vue/">Vue</a></div><div class="post_share"><div class="social-share" data-image="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/z8/wallhaven-z82evv.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="/img/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="/img/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2022/11/09/ES6%E6%96%B0%E7%89%B9%E6%80%A7/"><img class="prev-cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/j3/wallhaven-j3qq15.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">ES6新特性</div></div></a></div><div class="next-post pull-right"><a href="/2022/08/08/JavaScript/JavaScript%E5%8E%9F%E5%9E%8B%E5%92%8C%E5%8E%9F%E5%9E%8B%E9%93%BE/index/"><img class="next-cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/z8/wallhaven-z82evv.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">JavaScript原型和原型链</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2022/07/13/Vue/Vue%20Router/vueRouter/" title="Vue 路由"><img class="cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/ne/wallhaven-ne8mzl.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-13</div><div class="title">Vue 路由</div></div></a></div><div><a href="/2022/07/13/Vue/Vue%20%E5%93%8D%E5%BA%94%E5%BC%8F%E5%8E%9F%E7%90%86/Vue%E5%93%8D%E5%BA%94%E5%BC%8F%E5%8E%9F%E7%90%86/" title="Vue 响应式原理"><img class="cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/j3/wallhaven-j3qq15.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-13</div><div class="title">Vue 响应式原理</div></div></a></div><div><a href="/2022/07/15/Vue/Vue%20%E6%9C%8D%E5%8A%A1%E5%99%A8%E6%B8%B2%E6%9F%93/Vue%E6%9C%8D%E5%8A%A1%E7%AB%AF%E6%B8%B2%E6%9F%93/" title="Vue 服务器渲染"><img class="cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/ne/wallhaven-ne8mzl.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-15</div><div class="title">Vue 服务器渲染</div></div></a></div><div><a href="/2022/07/15/Vue/Vue%20%E6%BA%90%E7%A0%81%E8%A7%A3%E8%AF%BB/Vue%E6%BA%90%E7%A0%81%E8%A7%A3%E8%AF%BB/" title="Vue 源码解读"><img class="cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/j3/wallhaven-j3qq15.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-15</div><div class="title">Vue 源码解读</div></div></a></div><div><a href="/2022/07/15/Vue/Vue%20%E8%99%9A%E6%8B%9Fdom/Vue%20%E8%99%9A%E6%8B%9Fdom/" title="Vue 虚拟DOM"><img class="cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/k7/wallhaven-k7jmg6.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-15</div><div class="title">Vue 虚拟DOM</div></div></a></div><div><a href="/2022/07/15/Vue/Vue%20%E5%B8%B8%E8%A7%81%E9%9D%A2%E8%AF%95%E9%A2%98/Vue%E9%9D%A2%E8%AF%95%E9%A2%98/" title="Vue 面试题"><img class="cover" src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/yj/wallhaven-yj1kgl.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-15</div><div class="title">Vue 面试题</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="https://portrait.gitee.com/uploads/avatars/user/2982/8948190_JIAXInT_1624177607.png!avatar200" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Justic</div><div class="author-info__description">最是人间留不住 朱颜辞镜花辞树</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">25</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">2</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">3</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%80%E3%80%81%E4%BB%80%E4%B9%88%E6%98%AF%E5%93%8D%E5%BA%94%E5%BC%8F%EF%BC%9F"><span class="toc-text">一、什么是响应式？</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%8C%E3%80%81%E5%93%8D%E5%BA%94%E5%BC%8F%E5%87%BD%E6%95%B0%E8%AE%BE%E8%AE%A1"><span class="toc-text">二、响应式函数设计</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%89%E3%80%81%E5%93%8D%E5%BA%94%E5%BC%8F%E5%87%BD%E6%95%B0%E7%9A%84%E5%AE%9E%E7%8E%B0watchFn"><span class="toc-text">三、响应式函数的实现watchFn</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%9B%9B%E3%80%81%E5%93%8D%E5%BA%94%E5%BC%8F%E4%BE%9D%E8%B5%96%E7%9A%84%E6%94%B6%E9%9B%86"><span class="toc-text">四、响应式依赖的收集</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%94%E3%80%81%E7%9B%91%E5%90%AC%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%8F%98%E5%8C%96"><span class="toc-text">五、监听对象的变化</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%85%AD%E3%80%81%E5%AF%B9%E8%B1%A1%E7%9A%84%E4%BE%9D%E8%B5%96%E7%AE%A1%E7%90%86"><span class="toc-text">六、对象的依赖管理</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%83%E3%80%81%E5%AF%B9%E8%B1%A1%E4%BE%9D%E8%B5%96%E7%AE%A1%E7%90%86%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="toc-text">七、对象依赖管理的实现</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%85%AB%E3%80%81%E6%AD%A3%E7%A1%AE%E7%9A%84%E4%BE%9D%E8%B5%96%E6%94%B6%E9%9B%86"><span class="toc-text">八、正确的依赖收集</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B9%9D%E3%80%81%E5%AF%B9Depend%E9%87%8D%E6%9E%84"><span class="toc-text">九、对Depend重构</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8D%81%E3%80%81%E5%88%9B%E5%BB%BA%E5%93%8D%E5%BA%94%E5%BC%8F%E5%AF%B9%E8%B1%A1"><span class="toc-text">十、创建响应式对象</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8D%81%E4%B8%80%E3%80%81Vue2%E3%80%81Vue3%E5%93%8D%E5%BA%94%E5%BC%8F%E5%8E%9F%E7%90%86"><span class="toc-text">十一、Vue2、Vue3响应式原理</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2022/11/09/JavaScript/ES6%E6%96%B0%E7%89%B9%E6%80%A7/index/" title="ES6新特性"><img src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/m9/wallhaven-m9y289.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="ES6新特性"/></a><div class="content"><a class="title" href="/2022/11/09/JavaScript/ES6%E6%96%B0%E7%89%B9%E6%80%A7/index/" title="ES6新特性">ES6新特性</a><time datetime="2022-11-09T12:55:33.000Z" title="发表于 2022-11-09 20:55:33">2022-11-09</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/11/09/123/" title="123"><img src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/z8/wallhaven-z82evv.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="123"/></a><div class="content"><a class="title" href="/2022/11/09/123/" title="123">123</a><time datetime="2022-11-09T12:40:11.000Z" title="发表于 2022-11-09 20:40:11">2022-11-09</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/11/09/ES6%E6%96%B0%E7%89%B9%E6%80%A7-1/" title="ES6新特性"><img src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/z8/wallhaven-z82evv.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="ES6新特性"/></a><div class="content"><a class="title" href="/2022/11/09/ES6%E6%96%B0%E7%89%B9%E6%80%A7-1/" title="ES6新特性">ES6新特性</a><time datetime="2022-11-09T12:38:06.000Z" title="发表于 2022-11-09 20:38:06">2022-11-09</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/11/09/ES6%E6%96%B0%E7%89%B9%E6%80%A7/" title="ES6新特性"><img src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/j3/wallhaven-j3qq15.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="ES6新特性"/></a><div class="content"><a class="title" href="/2022/11/09/ES6%E6%96%B0%E7%89%B9%E6%80%A7/" title="ES6新特性">ES6新特性</a><time datetime="2022-11-09T12:35:33.000Z" title="发表于 2022-11-09 20:35:33">2022-11-09</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/10/20/Vue/Vue%20%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/Vue%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/" title="Vue 响应式解析"><img src= "" data-lazy-src="https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/z8/wallhaven-z82evv.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Vue 响应式解析"/></a><div class="content"><a class="title" href="/2022/10/20/Vue/Vue%20%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/Vue%E5%93%8D%E5%BA%94%E5%BC%8F%E8%A7%A3%E6%9E%90/" title="Vue 响应式解析">Vue 响应式解析</a><time datetime="2022-10-20T12:05:37.000Z" title="发表于 2022-10-20 20:05:37">2022-10-20</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://dogefs.s3.ladydaily.com/~/source/wallhaven/full/z8/wallhaven-z82evv.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By Justic</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a><img src= "" data-lazy-src="https://static.dy208.cn/o_1dfilp8ruo521thr1hvf18ji17soa.png">
<a href="http://www.beian.miit.gov.cn/"  style="color:#f72b07" target="_blank">晋ICP备2021014440号-2</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="聊天"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'KgIigedIwh0GobYsWWfPMEdO-gzGzoHsz',
      appKey: 'WpJEQP22asTau19i2tq1yQhU',
      avatar: 'justic',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !false) {
  if (false) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><div class="aplayer no-destroy" data-id="5076309057" data-server="netease" data-type="playlist" data-fixed="true" data-autoplay="true" data-lrcType="-1"> </div><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-nest.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = true;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-show-text.min.js" data-mobile="true" data-text="富强,民主,文明,和谐,平等,公正,法治,爱国,敬业,诚信,友善" data-fontsize="15px" data-random="true" async="async"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --><script data-pjax>
  function butterfly_clock_anzhiyu_injector_config(){
    var parent_div_git = document.getElementsByClassName('sticky_layout')[0];
    var item_html = '<div class="card-widget card-clock"><div class="card-glass"><div class="card-background"><div class="card-content"><div id="hexo_electric_clock"><img class="entered loading" id="card-clock-loading" src= "" data-lazy-src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/loading.gif" style="height: 120px; width: 100%;" data-ll-status="loading"/></div></div></div></div></div>';
    console.log('已挂载butterfly_clock_anzhiyu')
    parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = 'all';
  var qweather_key = 'f854dfdd82d747fca7fd04f092861e87';
  var gaud_map_key = '427416c518f4476a01117be40057a892';
  var baidu_ak_key = 'undefined';
  var flag = 0;
  var clock_rectangle = '112.982279,28.19409';
  var clock_default_rectangle_enable = 'false';

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_clock_anzhiyu_injector_config();
  }
  else if (epage === cpage){
    butterfly_clock_anzhiyu_injector_config();
  }
  </script><script src="https://widget.qweather.net/simple/static/js/he-simple-common.js?v=2.0"></script><script data-pjax src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.js"></script><!-- hexo injector body_end end --></body></html>